<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="角色标识" prop="roleKey">
        <el-input v-model="queryParams.roleKey" placeholder="请输入角色标识" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="角色状态" clearable style="width: 240px">
          <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:role:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['system:role:update']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:role:delete']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="角色编号" prop="id" width="120" />
      <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="角色标识" prop="roleKey" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="角色描述" prop="roleDescription" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="显示顺序" prop="roleSort" width="100" />
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="修改" placement="top" v-if="scope.row.roleId !== 1">
            <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:role:update']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" v-if="scope.row.roleId !== 1">
            <el-button type="text" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:role:delete']"></el-button>
          </el-tooltip>
          <el-tooltip content="分配用户" placement="top" v-if="scope.row.roleId !== 1">
            <el-button type="text" icon="User" @click="handleAuthUser(scope.row)" v-hasPermi="['system:role:update']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="roleKey">
          <template #label>
            <span>
              <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top"> </el-tooltip>
              权限字符
            </span>
          </template>
          <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="资源权限">
          <el-tree
            default-expand-all
            class="tree-border"
            :data="resOptions"
            show-checkbox
            check-strictly
            ref="resRef"
            node-key="permission"
            :default-checked-keys="checkedKeys"
            empty-text="加载中，请稍候"
            :props="{ label: 'resName', children: 'children' }"
          ></el-tree>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="form.roleDescription" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Role">
import { createOne, deleteOne, queryOne, queryList, updateOne } from "@/api/system/role";
import { treeSelect as resTree } from "@/api/system/res";
import { ref } from "vue";

const router = useRouter();
const { proxy } = getCurrentInstance();
// const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const sys_normal_disable = ref([
  {
    value: 1,
    label: "启用",
  },
  {
    value: 0,
    label: "未启用",
  },
]);
const tableList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const resOptions = ref([]);
const resRef = ref(null);
const checkedKeys = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    roleName: undefined,
    roleKey: undefined,
    status: undefined,
  },
  rules: {
    roleName: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
    roleKey: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
    roleSort: [{ required: true, message: "角色顺序不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询角色列表 proxy.addDateRange(queryParams.value, dateRange.value) */
function getList() {
  loading.value = true;
  queryList(queryParams.value).then((response) => {
    tableList.value = response.content;
    total.value = response.totalElements;
    loading.value = false;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
  const roleIds = row.id ? [row.id] : ids.value;
  proxy.$modal
    .confirm('是否确认删除角色编号为"' + roleIds + '"的数据项?')
    .then(function () {
      let task = [];
      roleIds.forEach(function (ele, index) {
        task.push(deleteOne(ele));
      });
      return new Promise(function (resolve, reject) {
        Promise.all(task).then((res) => {
          resolve(res);
        });
      });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 角色状态修改 */
function handleStatusChange(row) {
  let text = row.status === 0 ? "停用" : "启用";
  const data = row;
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.roleName + '"角色吗?')
    .then(function () {
      return updateOne(data);
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function () {
      row.status = row.status === 0 ? 1 : 0;
    });
}
/** 分配用户 */
function handleAuthUser(row) {
  router.push("/system/role-grant/" + row.id);
}
/**
 * 构建选择树
 * @param {*} arr
 */
function buildResTree(arr) {
  return arr.map((ele) => {
    if (ele.permission == undefined || ele.permission == null || ele.permission == "") {
      ele.disabled = true;
    }
    if (ele.children != undefined && ele.children != null && ele.children.length > 0) {
      ele.children = buildResTree(ele.children);
    }
    return ele;
  });
}
/** 查询菜单树结构 */
function getResTree() {
  return new Promise(function (resolve, reject) {
    resTree().then((response) => {
      resOptions.value = buildResTree(response);
      resolve(resOptions.value);
    });
  });
}
/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    id: undefined,
    permissions: [],
    roleDescription: undefined,
    roleKey: undefined,
    roleName: undefined,
    roleSort: undefined,
    status: undefined,
  };
  proxy.resetForm("formRef");
}
/** 添加角色 */
function handleAdd() {
  reset();
  getResTree();
  checkedKeys.value = [];
  open.value = true;
  title.value = "添加角色";
}
/** 修改角色 */
function handleUpdate(row) {
  reset();
  const roleId = row.id || ids.value;
  queryOne(roleId).then((response) => {
    form.value = response;
    form.value.roleSort = Number(form.value.roleSort);
    open.value = true;
    getResTree().then((res) => {
      // resOptions.value = res;
      checkedKeys.value = response.permissions;
      //console.log(checkedKeys.value);
      // this.$resRef.tree.setCheckedKeys(response.permissions);
    });

    title.value = "修改角色";
  });
}

/** 所有菜单节点数据 */
function getResAllCheckedKeys() {
  // 目前被选中的菜单节点
  let checkedKeys = resRef.value.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = resRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        form.value.permissions = getResAllCheckedKeys();
        updateOne(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        form.value.menuIds = getResAllCheckedKeys();
        createOne(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

getList();
</script>
